import Foundation

enum CommandType: String {
    case lightOn = "L:ON"
    case lightOff = "L:OFF"
    case servoAngle = "S:"
    case moveForward = "M:F"
    case moveBackward = "M:B"
    case turnLeft = "M:L"
    case turnRight = "M:R"
}

func sendCommand(command: CommandType, angle: Int? = nil) {
    var commandString = command.rawValue
    
    // 如果是舵机角度命令，则附加角度值
    if let angle = angle, command == .servoAngle {
        commandString += "\(angle)"
    }
    
    guard let url = URL(string: "http://\(getESP32IPAddress()):80/\(commandString)") else {
        print("Invalid URL")
        return
    }
    
    var request = URLRequest(url: url)
    request.httpMethod = "GET"
    
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        if let error = error {
            print("Error: \(error)")
            return
        }
        
        if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 {
            print("Command sent successfully")
        } else {
            print("Failed to send command")
        }
    }
    
    task.resume()
}

func getESP32IPAddress() -> String {
    // 这里返回ESP32的IP地址
    // 假设ESP32的IP地址为192.168.4.1（默认AP模式下的IP）
    return "192.168.4.1"
}
